package com.czm.art_light.param.response;

import com.czm.art_light.constant.ArtErrorCodeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;

import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;

/**
 * Http Rest 响应工具及数据格式封装
 */
@Schema(description = "Http Rest 响应工具及数据格式封装")
@Getter
public class RestResp<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 响应码
     */
    @Schema(description = "响应码")
    private final String code;

    /**
     * 响应消息
     */
    @Schema(description = "响应消息")
    private final String message;

    /**
     * 响应数据
     */
    @Schema(description = "响应数据")
    private T data;

    private RestResp() {
        this.code = ArtErrorCodeEnum.OK.getCode();
        this.message = ArtErrorCodeEnum.OK.getMessage();
    }

    private RestResp(ArtErrorCodeEnum errorCode) {
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
        this.data = null; // 默认情况下，错误码不携带数据
    }

    private RestResp(T data) {
        this();
        this.data = data;
    }

    /**
     * 业务处理成功,无数据返回
     */
    public static RestResp<Void> ok() {
        return new RestResp<>();
    }

    /**
     * 业务处理成功，有数据返回
     */
    public static <T> RestResp<T> ok(T data) {
        return new RestResp<>(data);
    }

    /**
     * 业务处理失败
     */
    public static <T> RestResp<T> fail(ArtErrorCodeEnum errorCode) {
        return new RestResp<>(errorCode);
    }

    /**
     * 系统错误
     */
    public static RestResp<Void> error() {
        return new RestResp<>(ArtErrorCodeEnum.SYSTEM_ERROR);
    }

    /**
     * 判断是否成功
     */
    public boolean isOk() {
        return Objects.equals(this.code, ArtErrorCodeEnum.OK.getCode());
    }
}